<template>
  <div>
    <div class="search">
      <input v-model="keyword"  class="search-input" placeholder="输入城市名或拼音"/>
    </div>
    <div class="search-content" ref="search-content" v-show="keyword">
      <ul>
        <li class="search-item border-bottom" v-for="city in list" :key="city.id"   @click="handleCityClick(city.name)">{{city.name}}</li>
        <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
      </ul>
    </div>
  </div>
</template>

<script>
import Bscroll from 'better-scroll'
export default {
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [],
      timer: null
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity', city)
      this.$router.push('/')
    }
  },
  components: {},
  computed: {
    hasNoData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }

      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((cityItem) => {
            if (cityItem.spell.indexOf(this.keyword) > -1 || cityItem.name.indexOf(this.keyword) > -1) {
              result.push(cityItem)
            }
          })
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.bscroll = new Bscroll(this.$refs['search-content'])
  }
}
</script>

<style lang="stylus" scoped>
  @import "~styles/varibles.styl"
  .search
    line-height :0.72rem
    height :0.72rem
    background-color :$bgColor
    padding :0.1rem
    .search-input
      box-sizing :border-box
      line-height :0.62rem
      text-align :center
      border-radius :0.06rem
      width :100%
      padding :0 0.1rem
  .search-content
    overflow :hidden
    z-index :1
    position: absolute
    top:1.78rem
    left :0rem
    right :0rem
    bottom :0rem
    background :#eee
    .search-item
      height :0.62rem
      line-height :0.62rem
      padding-left :0.2rem
      background :#fff
      color :#666
</style>
